from flask import Flask, request, jsonify
from getInfo import get_info
import threading
from ip import get_ip
import queue
from oldinfo import old_info
import web_uuid,getBasicEnterprise,getPolicyEnterprise
from forcompany import get_forcompany
from checkUrlAccess import get_access

app = Flask(__name__)
app.config['THREADING'] = True
result_queue = queue.Queue()

result=[]
@app.route('/api/data', methods=['GET'])
def get_data():
    global result
    name = request.args.get('name', default='', type=str)
    cridecode = request.args.get('cridecode', default='', type=str)
    print(f'获取到信息内容name: {name},cridecode: {cridecode}')
    # if len(result)<2:
    #     result=get_ip()
    # ip= result[0].get('ip')
    # port= result[0].get('port')
    # del result[0]

    def handle_request(name, cridecode, ip=None, port=None):
        
        webid=web_uuid.webid()

        info = get_info(webid,name, cridecode, ip, port)
        forcompant=get_forcompany(cridecode)
        print('info',info)
        id = info['data']['id']
        old = old_info(webid,name,cridecode,id)
        getBasic=getBasicEnterprise.get_Basic(webid,name,id)
        getPolicy=getPolicyEnterprise.get_Policy(webid,id)

        data={
            "info": info,
            "old": old,
            "getBasic": getBasic,
            "getPolicy": getPolicy,
            "forcompant": forcompant
        }

        result_queue.put(jsonify(data))

    def thread_target():
        with app.app_context():
            handle_request(name, cridecode)

    thread = threading.Thread(target=thread_target)
    thread.start()

    # 等待线程完成
    thread.join()

    # 从队列中获取结果并返回
    response = result_queue.get()
    return response


@app.route('/api/checkurl',methods=['GET'])
def get_checkUrl():
    id = request.args.get('id', default='', type=str)
    def handle_request(id):
        data = get_access(id)  # 假设这个函数返回一些数据
        print('类型',type(data))
        datas={
            "datas":data
        }
        result_queue.put(jsonify(data))  # 将数据放入队列

    def thread_target():
        with app.app_context():
            handle_request(id)

    thread = threading.Thread(target=thread_target)
    thread.start()

    # 等待线程完成
    thread.join()

    # 从队列中获取结果并返回
    try:
        response = result_queue.get_nowait()  # 使用 get_nowait 来避免阻塞，或者使用 get 并设置超时
    except queue.Empty:
        response = jsonify({'error': 'No data available'})  # 如果队列为空，返回错误信息

    return response
if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8009, debug=False)